package cn.wizzer.app.onlyoffice.modules.services.impl.callback;

import cn.wizzer.app.bus.modules.models.BusinessFileInfo;
import cn.wizzer.app.bus.modules.services.BusinessFileInfoService;
import cn.wizzer.app.onlyoffice.modules.models.documentServer.Status;
import cn.wizzer.app.onlyoffice.modules.services.Callback;
import cn.wizzer.app.onlyoffice.modules.utils.HttpUtil;
import cn.wizzer.app.onlyoffice.modules.utils.MD5Util;
import cn.wizzer.app.web.commons.base.Globals;
import cn.wizzer.app.web.modules.controllers.open.file.UploadController;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Times;

import java.io.FileOutputStream;
import java.io.OutputStream;

@IocBean
public class SaveCallback implements Callback {
    @Inject
    private MD5Util md5Util;
    @Inject
    private BusinessFileInfoService businessFileInfoService;

    @Override
    public int handle(cn.wizzer.app.onlyoffice.modules.dto.Callback body, String fileId) {
        BusinessFileInfo report = businessFileInfoService.fetch(fileId);
        byte[] bytes = HttpUtil.downloadFile(body.getUrl(), null);
        try {
            String filePath = report.getFilePath();
            String uploadPath = this.getUploadPathConfig();
            String path = uploadPath + filePath;
            // 使用 try-with-resources 确保输出流在结束时被关闭
            try (OutputStream outs = new FileOutputStream(path)) {
                outs.write(bytes);
            }
            report.setOpAt(Times.getTS());
            businessFileInfoService.update(report);
        // 历史记录信息
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int getStatus() {
        return Status.SAVE.getCode();
    }


    private String getUploadPathConfig() throws Exception {
        String uploadPath;
        //系统没开启配置,上传到项目路径
        if ("false".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false"))) {
            uploadPath = UploadController.class.getClassLoader().getResource("").getPath() + "upload";
        } else if (
                ("true".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false"))) && (Globals.MyConfig.getOrDefault("ConfigUploadPath", null) != null)
        ) {
            uploadPath = Globals.MyConfig.get("ConfigUploadPath").toString();
        } else {
            throw new Exception("文件上传路径配置有误");
        }
        return uploadPath;
    }
}
